package cheme.ProcessModel.ProcessUnits.Streams.Tags;

import java.io.Serializable;
import java.util.List;

import cheme.ProcessModel.AbstractParent;


public class TagComponentInitPolicy implements ITagComponentInitPolicy, Serializable
{
	/*
	 * Serialization version identifier. (Set to default for now)
	 */
	
	private static final long serialVersionUID = 1L;
	
	OverallTagComponent base = null;
	
	AbstractParent parent = null;
	
	transient int currentId = 0;
	
	public TagComponentInitPolicy(OverallTagComponent base, AbstractParent parent)
	{
		this.base = base;
		this.parent = parent;
	}
	
	public void init(Object toInit)
	{
		Init((TagComponent)toInit);
	}
	
	public void Init(TagComponent toInit)
	{
		if(null != toInit)
		{
			if(toInit.getLabel().isEmpty())
			{
				toInit.setLabel(getLabel());
			}
			
			toInit.setQuantity(getQuantity());
			
			/*
			 * For the moment, overall components initially have a different initial units
			 * than components do.
			 */
			//toInit.setUnits(getUnits());
		}
	}

	public void setCurrentId(int num)
	{
		this.currentId = num;
	}
	
	private int getNextId()
	{
		/*
		 * if the max Id has not been calculated yet, do that by looking at each child's id.
		 */
				
		if(0 == currentId)
		{
			List<IGeneralTagComponent> children = parent.getChildren();
			
			for(ITagComponent child : children)
			{
				currentId = Math.max(currentId, getnumberSuffix(child.getLabel()));
			}
		}
		
		return ++currentId;
	}
	
	private int getnumberSuffix(String identifier)
	{
		StringBuilder b = new StringBuilder();
		
		for(int i = identifier.length() - 1; i >= 0; i--)
		{
			if(Character.isDigit(identifier.charAt(i)))
			{
				b.insert(0, identifier.charAt(i));
			}
		}
		
		if(!b.toString().isEmpty())
		{
			return Integer.parseInt(b.toString());
		}
		
		return 0;
	}
	
	public String getLabel()
	{
		if(null != base)
		{
			String identifier = base.getLabel();
			
			/*
			 * Might process
			 */
			
//			StringTokenizer st = new StringTokenizer(identifier);
//			while (st.hasMoreTokens())
//		    {
//		         //process token...
//		    }
		     
			return identifier.toLowerCase() + Integer.toString(getNextId());
		}
		
		return "m1";
	}
	
	public String getQuantity()
	{
		return "?"; // PA change from "" -> "?"
	}
	
	public String getUnits()
	{
		return base.getUnits();
	}
}
